
package com.album.activity;

 import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.album.R; 
import com.album.activity.base.BaseActivity;
import com.album.activity.page.PageManager;
import com.album.utils.MyLog;

import android.app.Activity;
import android.app.ActivityGroup;
import android.app.LocalActivityManager;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;
 
 
public class CopynitiveManagerActivity extends BaseActivity  {
   
	public static CopynitiveManagerActivity instance;
	private ArrayList<String> filelist = new ArrayList<String>();	//文件夹
	private FolderAdapter adapter;
	private ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
	private GridView  folderList;
	private ProgressDialog dialog;
	
	private List<String> filePaths = new ArrayList<String>();
	private List<String> imageCounts = new ArrayList<String>();
	private BitmapFactory.Options options;
	
	private List<String> paths ; //path:/mnt/sdcard/DCIM/100MEDIA/IMAG0002.jpg
	private List<Bitmap> folderBitmaps; 
	private int index;
//	private Bitmap defaultBitmap;
	public static ArrayList<HashMap<String, String>> pathList = new ArrayList<HashMap<String, String>>(); 
	private ViewFlipper viewflipper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nitive_manager);
		instance = this;
		opts.inJustDecodeBounds = true; 
		opts.inSampleSize = computeSampleSize(opts, -1, 128*128);	
		opts.inJustDecodeBounds = false;
		opts.inSampleSize = 5;
		init();
	}
	
	public void init(){ 
//		defaultBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
		folderList = (GridView) findViewById(R.id.folderList); 
		folderList.setGravity(Gravity.CENTER);// 位置居中 
		viewflipper = (ViewFlipper)findViewById(R.id.viewflipper);
		options = new BitmapFactory.Options();
		// 跳转到图片选择界面
		folderList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				String filepath = filePaths.get(position);
				String imageCount = imageCounts.get(position);
				MyLog.debug(getClass(), "filepath:"+filepath);
				MyLog.debug(getClass(), "imageCount:"+imageCount);

				Intent intent = new Intent(CopynitiveManagerActivity.this,ImageFolderListActivity.class);
				intent.putExtra("filePath", filepath);
				intent.putExtra("fileCount", imageCount);
//				startActivity(intent);
				startActivityForResult(intent,2);
				
//				backEvent(filePaths.get(position), imageCounts.get(position));
			}
		});
		
		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
			if (dialog == null) {
				dialog = ProgressDialog.show(this, "", "正在加载...", true);
			} else {
				dialog.show();
			}
			new loadingImageFolder().execute();
		} else {
			Toast.makeText(instance, "sd_error", Toast.LENGTH_SHORT).show();
		}
		viewflipper.setDisplayedChild(1);
	} 
	
	private void returnMain(){
		Intent intent = new Intent(this, MainActivity.class);
		startActivityForResult(intent, 111);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { 
			returnMain();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	} 
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode==2){
			MyLog.debug(getClass(), "onActivityResult...");
			viewflipper.setDisplayedChild(1);
		}
	}
	private void findImage() {
		Uri originalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		ContentResolver cr = this.getContentResolver();
		Cursor cursor = cr.query(originalUri, null, null, null, null);
		cursor.moveToFirst();
		String tempString, string,path;
		// int id;
		// 获取有图片的文件夹名称
		try {
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				// id = cursor.getInt(cursor.getColumnIndex("_ID"));
				path = cursor.getString(cursor.getColumnIndex("_data"));
				tempString = path.substring(0, path.lastIndexOf("/"));
				// string是图片文件夹的完整路径
				string = tempString.substring(tempString.lastIndexOf("/") + 1);
				// 添加文件夹名称，并将这个文件夹下面的图片数设为1.
				if (!filelist.contains(string)) {
					filelist.add(string);
					//添加图片文件夹的完整路径
					filePaths.add(tempString);
					
					//string:100MEDIA    
					//tempString:/mnt/sdcard/DCIM/100MEDIA    
					//path:/mnt/sdcard/DCIM/100MEDIA/IMAG0002.jpg
					
					imageCounts.add(filelist.indexOf(string), String.valueOf(1));
//					MyLog.debug(getClass(), 
//							"string:"+string+"\t"+
//							"tempString:"+tempString+"\t"+
//							"path:"+path);
					MyLog.info(getClass(), "path:"+path);
					paths.add(path);
				} else {
					// 已有这个文件夹名称，将这个文件夹下的图片数加1.
					imageCounts.set(filelist.indexOf(string), Integer.parseInt(imageCounts
							.get(filelist.indexOf(string)))
							+ 1 + "");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (cursor != null) {
			cursor.close();
		}
	}

	private void setAdapter() {
		HashMap<String, Object> map;

		for (int i = 0; i < filelist.size(); i++) {
			map = new HashMap<String, Object>();
			map.put("name", filelist.get(i));
			map.put("image", "" + i);
			map.put("count", "(" + imageCounts.get(i) + ")");
			data.add(map);
			MyLog.debug(getClass(), "name:"+filelist.get(i));
			MyLog.debug(getClass(), "count:"+"(" + imageCounts.get(i) + ")");
			map = null;
		}
		adapter = new FolderAdapter(this, data, R.layout.folder_list_item, new String[] { "name", "image", "count" },
				new int[] { R.id.pathText, R.id.folderImage, R.id.countText });
		folderList.setAdapter(adapter);
		index = 0;
	}

	BitmapFactory.Options opts = new BitmapFactory.Options(); 
	
	class loadingImageFolder extends AsyncTask<Integer,Integer,Integer>{ 
		
		@Override
		protected Integer doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			try {
				if (folderList.getAdapter() == null) { 
					folderBitmaps = new ArrayList<Bitmap>();
					paths = new ArrayList<String>();
					findImage();
					HashMap<String, Object> map;
					for (int i = 0; i < filelist.size(); i++) {
						map = new HashMap<String, Object>();
						map.put("name", filelist.get(i));
						map.put("image", "" + i);
						map.put("count", "(" + imageCounts.get(i) + ")");
						data.add(map);
//						MyLog.debug(getClass(), "name:"+filelist.get(i));
//						MyLog.debug(getClass(), "count:"+"(" + imageCounts.get(i) + ")");
						map = null;
					}
					this.publishProgress(RESULT_OK);
					MyLog.info(getClass(), "***************pathsSize:"+""+paths.size());
					
					for (String pathName : paths) { 
						MyLog.info(getClass(), "pathName:"+pathName);
						if (pathName != null) {
							Bitmap bmp=BitmapFactory.decodeFile(pathName,opts);
							if(bmp!=null)
								folderBitmaps.add(bmp);
								this.publishProgress(RESULT_CANCELED); 
						}
					}
				} 
			} catch (Exception e) {
				return DEFAULT_KEYS_SHORTCUT;
			}
			return RESULT_OK;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub 
			if(values!=null){
				MyLog.debug(getClass(), "values:"+values[0]);
				if(values[0] == RESULT_OK){
					adapter = new FolderAdapter(CopynitiveManagerActivity.this, data, R.layout.folder_list_item, new String[] { "name", "image", "count" },
							new int[] { R.id.pathText, R.id.folderImage, R.id.countText });
					folderList.setAdapter(adapter);
					index = 0;
				}
				else if(values[0] == RESULT_CANCELED ){
					if (adapter != null)
						MyLog.info(getClass(), "notifyDataSetChanged...");
						adapter.notifyDataSetChanged(); 
				}
			}
			
		}
		@Override  
	    protected void onCancelled() {  
			super.onCancelled();  
	    }  
		 
		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub 
			if(result!=DEFAULT_KEYS_SHORTCUT){ 
			}
			if (dialog != null) {
				dialog.dismiss();
				dialog = null;
			}
		}
	}
	 
	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
			double w = options.outWidth;
			double h = options.outHeight;

			int lowerBound = (maxNumOfPixels == -1) ? 1 :
			(int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
			int upperBound = (minSideLength == -1) ? 128 :
			(int) Math.min(Math.floor(w / minSideLength),
			Math.floor(h / minSideLength));

			if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
			}

			if ((maxNumOfPixels == -1) &&
			(minSideLength == -1)) {
			return 1;
			} else if (minSideLength == -1) {
			return lowerBound;
			} else {
			return upperBound;
			}
			}	
	public static int computeSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
			int initialSize = computeInitialSampleSize(options, minSideLength,
			maxNumOfPixels);

			int roundedSize;
			if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
			roundedSize <<= 1;
			}
			} else {
			roundedSize = (initialSize + 7) / 8 * 8;
			}

			return roundedSize;
	}
	
	private void setAdapterImages(){
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true; 
		opts.inSampleSize = computeSampleSize(opts, -1, 128*128);	
		opts.inJustDecodeBounds = false;
		opts.inSampleSize = 10;
		
		folderBitmaps = new ArrayList<Bitmap>();
		MyLog.info(getClass(), "pathsSize:"+paths.size());
		
		for (String pathName : paths) { 
//			if (pathName.contains("100ANDRO")) {
//				options.inSampleSize = 2;
//			} else {
//				options.inSampleSize = 2;
//			}
				MyLog.info(getClass(), "pathName:"+pathName);
				if (pathName != null) {
					Bitmap bmp=BitmapFactory.decodeFile(pathName,opts);
					folderBitmaps.add(bmp);
				}
				if (adapter != null) {
					MyLog.info(getClass(), "notifyDataSetChanged...");
					adapter.notifyDataSetChanged();
				}
				
		}
	}
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (dialog != null) {
				dialog.dismiss();
				dialog = null;
			}
			if (msg.what == 1) {
				setAdapter();
				setAdapterImages();
			} else if (msg.what == 2) {
				if (adapter != null) {
					MyLog.info(getClass(), "notifyDataSetChanged...");
					adapter.notifyDataSetChanged();
				}
			}
		}
	};
	
	
	 

	private void backEvent(String extraString, String imageCount) {
//		Intent intent = new Intent(ImageFolderList.this, cls);
//		if (extraString != null) {
//			intent.putExtra("filePath", extraString);
//			intent.putExtra("fileCount", Integer.parseInt(imageCount));
//		}
		finish();
	}

	class FolderAdapter extends SimpleAdapter {
		public FolderAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			index = position;
			return super.getView(position, convertView, parent);
		}

		@Override
		public void setViewImage(ImageView v, String value) {
			try {
				v.setImageBitmap(null);
				if (folderBitmaps != null && index < folderBitmaps.size() && folderBitmaps.get(index) != null
						&& !folderBitmaps.get(index).isRecycled()) {
					v.setImageBitmap(folderBitmaps.get(index));
				}
			} catch (IndexOutOfBoundsException e) {
				e.printStackTrace();
			}
		}

	}
	
	public void recycledFolderBitmaps(){
		try {
			if (folderBitmaps != null && folderBitmaps.size() > 0) {
				for (int i = 0, l = folderBitmaps.size(); i < l; i++) {
					if (folderBitmaps.get(i) != null && !folderBitmaps.get(i).isRecycled())
						folderBitmaps.get(i).recycle();
				}
				folderBitmaps.clear();
				folderBitmaps=null;
			}
		}catch (IndexOutOfBoundsException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		recycledFolderBitmaps();
		super.onDestroy();
	}
	 
}